# This Python file uses the following encoding: utf-8
import sys

from PySide6.QtWidgets import QApplication, QWidget, QFileDialog,QMessageBox
from PySide6.QtGui import QPixmap, QImage, QImageWriter
from PySide6.QtCore import Qt,QBuffer, QIODevice

# Important:
# You need to run the following command to generate the ui_form.py file
#     pyside6-uic form.ui -o ui_form.py, or
#     pyside2-uic form.ui -o ui_form.py
from ui_form import Ui_WinWidget
from ocrtool import OcrTool
class Widget(QWidget):
    #读取文件
    def open_file(self):
        file_path,_ = QFileDialog.getOpenFileName(self,"选择图片","","图片文件(*.png *.jpg *.jpeg")
        if file_path:
            pixmap = QPixmap(file_path)
            origin_width = pixmap.width();
            scaled_pixmap = pixmap.scaledToWidth(500,Qt.SmoothTransformation)
            self.image = scaled_pixmap
            #scale = origin_width/scaled_pixmap.width()
            #self.ui.resultLabel.setText(str(scale))
            if not pixmap.isNull():
                self.ui.image_label.setPixmap(scaled_pixmap)
    def ocr_file(self):
        self.ui.resultList.clear()
        q_image = self.image.toImage()
        q_image = q_image.convertToFormat(QImage.Format.Format_RGB888)
        try:
            result, result_image = OcrTool.image_ocr(q_image)
            self.ui.image_label.setPixmap(QPixmap.fromImage(result_image))
            for text in result:
                self.ui.resultList.addItem(text)
        except Exception as err:
            QMessageBox.critical(self, "错误", str(err))
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_WinWidget()
        self.ui.setupUi(self)
        self.ui.selectFileBtn.clicked.connect(self.open_file)
        self.ui.ocrBtn.clicked.connect(self.ocr_file)
        self.image = QPixmap()
        self.scaled_pixmap = 1;
if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = Widget()
    widget.show()
    sys.exit(app.exec())

